var map;
var bombMarker;
var windMarker;
var detectMarker;
var myBlueIcon;
var localsearch;
var effects = new caculateEffects();
var sfss = new SFSS();
var psi = new OverpressureInterpolate();
var overlays = new Overlays();
var weather = new Weather();
var mouseposi;
// 定位控件
var geolocationcontrol;

if(debug) console.log('effects.ambient_pressure', effects.ambient_pressure);

const App = {
    data (){
        return{
            // 预设的城市及其经纬度
            // presetCitys:[
            //     {location:[38.89469253046311, -77.02189926086425], name:'华盛顿'},
            //     {location:[51.499167, -0.124722], name:'纽约'},
            //     {location:[40.72422, -73.9961], name:'伦敦'},
            // ],
            // // 历史上的爆炸地点及其经纬度
            // historicalLocations:[
            //     {location:'3 3', name:'test3'},
            //     {location:'4 4', name:'test4'}
            // ],
            // 选中的位置
            selectedLocation: '',
            // 输入的城市名称
            inputCity: '',
            // 输入的经度
            inputLng: '',
            inputLat: '',
            // 输入的纬度
            // 预设的核弹及其当量
            // presetYields:[
            //     {yield: 800, name:"Topol (SS-25) (800 kt)"},
            //     {yield: 1200, name:"B-83 (1.2 Mt)"},
            //     {yield: 3300, name:"Dong Feng-4 (3.3 Mt)"}
            // ],
            // 输入的当量（kt）
            inputYield: 800,
            // 选择的爆炸类型
            detonateType: 'SurfaceBurst',
            // 勾选的效应
            checkCasualty: false,
            checkFallout: true,
            // 高级选项参数
            // 空爆参数
            ab_option: '',
            ab_inputPress: '', // 单位：psi
            ab_inputHeight: '', 
            ab_selectedHUnit: 1, // 0: ft; 1: m; 2: mi; 3: km; 
            // 选择的超压环
            selectedPress: [],
            // 勾选了输入其他超压值
            otherPressChecked: false,
            // 输入的超压环超压
            inputPress: '',
            // 选择的电离辐射环
            selectedDose: [],
            // 勾选了输入其他电离辐射剂量值
            otherDoseChecked: false,
            // 输入的电离辐射环辐射剂量
            inputDose: '',
            // 选择的热辐射环
            selectedHeat: [],
            // 勾选了输入其他的单位面积热量
            otherHeatChecked: false,
            // 输入的热辐射环的单位面积热量
            inputHeat: '',
            // 勾选的其他选项
            selectFireball: true,
            selectCrater:  true,
            selectMushroom: true,
            selectAround: true,
            // 放射性落尘相关参数
            inputWindV: 5, // 当地风速
            inputWindA: '0', // 当地风向
            inputFissionFc: '100', //裂变份额
            doserates_out: '0.01, 1, 10, 100',
            doserates: [],
            // 弹坑大小相关参数
            crater_outr: 0,
            crater_insider: 0,
            crater_depth: 0,
            // 蘑菇云大小相关参数
            mushroom_h: 0,
            mushroom_a: 0,
            mushroom_b: 0,
            mushroom_rs: 0,
            // 爆炸周边设施相关参数
            facility: '医院',
            // 各效应显示相关参数
            showOrHide: true,
            isDoseShow: true,
            isThermalShow: true,
            isPressureShow: true,
            isFalloutShow: true,
            isDetectMarkerShow: false,
            // 探测标记信息窗口
            detectInfowindow: '',
            // 错误信息
            errinfo: '',
        };
    },
    
    mounted(){
        this.initMap();
        this.initSetting();
    },

    methods:{
        /*// initMap(){ // 高德地图api, 地图范围只包含国内
        //     AMapLoader.load({
        //         key: "aaa551f45cd283473193d3d46e0ea6be", // 申请好的Web端开发者Key，首次调用 load 时必填
        //         version: "2.0", // 指定要加载的 JSAPI 的版本，缺省时默认为 1.4.15
        //         plugins: [
        //             "AMap.Scale",
        //             "AMap.ToolBar",
        //             "AMap.MapType",
        //             "AMap.Geolocation",
        //             "AMap.PlaceSearch",
        //             "AMap.CircleEditor",
        //             "AMap.PolyEditor",
        //         ], // 需要使用的的插件列表，如比例尺'AMap.Scale'等
        //         AMapUI: {
        //             // 是否加载 AMapUI，缺省不加载
        //             version: "1.1", // AMapUI 版本
        //             plugins: ["overlay/SimpleMarker"], // 需要加载的 AMapUI ui插件
        //         },
        //         Loca: {
        //             // 是否加载 Loca， 缺省不加载
        //             version: "2.0", // Loca 版本
        //         },
        //     })
        //         .then((AMap) => {
        //             map = new AMap.Map("map",{
        //                 center: [116.40, 39.92],
        //             });
        //             // 插件实例化，加载插件 
        //             var scale = new AMap.Scale();
        //             map.addControl(scale);
        //             var toolbar = new AMap.ToolBar();
        //             map.addControl(toolbar);
        //             var maptype = new AMap.MapType();
        //             map.addControl(maptype);
        //             var geolocation = new AMap.Geolocation();
        //             map.addControl(geolocation);
        //             var placeSearch = new AMap.PlaceSearch();
        //             map.addControl(placeSearch);
        //             var circleEditor = new AMap.CircleEditor();
        //             map.addControl(circleEditor);
        //             var polyEditor = new AMap.PolyEditor();
        //             map.addControl(polyEditor);
        //         })
        //         .catch((e) => {
        //             console.error(e); //加载错误提示
        //         });
        //     //map.clearMap()
        // },*/

        // map初始化函数
        initMap(){
            map = new BMap.Map('map');
            map.enableScrollWheelZoom();
            let localcity =new BMap.LocalCity({map: map});
            let mapcenter;
            let that = this;
            // 根据用户IP定位地图中心点
            localcity.get(function(result){
                if(result){
                    mapcenter = new BMap.Point(result.center.lng, result.center.lat);
                    map.centerAndZoom(mapcenter, 12);
                }
                else{ // 如果IP定位失败
                    map.setCenter('纽约');
                    map.setZoom(12);
                    mapcenter = map.getCenter();
                    
                }
                bombMarker = new BMap.Marker(mapcenter);
                bombMarker.enableDragging();
                bombMarker.disableMassClear() 
                map.addOverlay(bombMarker);
                // console.log('result', result);
            });
            // BMap控件:
            map.addControl(new BMap.NavigationControl({type: BMAP_NAVIGATION_CONTROL_SMALL, anchor: BMAP_ANCHOR_BOTTOM_RIGHT}));        
            map.addControl(new BMap.OverviewMapControl());    
            map.addControl(new BMap.MapTypeControl({mapTypes: [BMAP_NORMAL_MAP, BMAP_SATELLITE_MAP]}));
            map.addControl(new BMap.ScaleControl());
            // 增加定位控件
            geolocationcontrol = new BMap.GeolocationControl({
                anchor: BMAP_ANCHOR_BOTTOM_RIGHT,
                showAddressBar: false,
            });
            geolocationcontrol.addEventListener("locationSuccess", function(e){
                that.setMapCenter(e.point);
                that.initSetting();
                overlays.clear();
            });
            geolocationcontrol.addEventListener("locationError", function(e){
                alert('locationError');
            });
            map.addControl(geolocationcontrol);
            // BMApGL控件:
            // map.addControl(new BMapGL.ScaleControl());
            // map.addControl(new BMapGL.ZoomControl());
            // map.addControl(new BMapGL.NavigationControl3D());
            map.addEventListener('mousemove', function(e){
                mouseposi = e.point;
                // console.log('mouseposi', mouseposi);
            });
            myBlueIcon = new BMap.Icon('../img/markers.png', new BMap.Size(18, 27),{imageOffset:new BMap.Size(-18, -22), anchor: new BMap.Size(9, 27)});
            myGreenIcon = new BMap.Icon('../img/markers.png', new BMap.Size(18, 27),{imageOffset:new BMap.Size(0, -22), anchor: new BMap.Size(9, 27)});
        },

        // 爆炸参数设置初始化函数
        initSetting(){
            this.selectedLocation =  '';
            this.inputCity = '';
            this.inputYield = '';
            this.inputLng = '';
            this.inputLat = '';
            this.detonateType = 'SurfaceBurst';
            this.checkCasualty = false;
            this.checkFallout = true;
            this.ab_option = 1;
            this.ab_inputPress = 0.34;
            this.ab_inputHeight = '';
            this.ab_selectedHUnit = 1;
            this.selectedPress = ['5', '20'];
            this.otherPressChecked = false;
            this.inputPress = '';
            this.selectedDose = ['100','500'];
            this.otherDoseChecked = false;
            this.inputDose = '';
            this.selectedHeat = ['3rd-100', '2nd-100'];
            this.otherHeatChecked = false;
            this.inputHeat = '';
            this.selectFireball = true;
            this.selectCrater = true;
            this.selectMushroom = true;
            this.selectAround = true;
            this,inputWindV = 5;
            this.inputWindA = 0;
            this.inputFissionFc = '100';
            this.doserates = '0.01, 1, 10, 100';
            this.searchFacility = false;
            this.facility = '医院';
            this.showOrHide = true;
            this.isDoseShow = true;
            this.isThermalShow = true;
            this.isPressureShow = true;
            this.isFalloutShow = true;
            this.initShowOrHide();

            // 防止鼠标滚轮更改输入当量值
            document.getElementById("yield-input").addEventListener('DOMMouseScroll', MouseWheel, false);
            function MouseWheel(event) {
                event = event || window.event;
                event.preventDefault();
            }
        },

        initShowOrHide(){
            let showdose_btn = document.getElementById('showdose');
            let showthermal_btn = document.getElementById('showthermal');
            let showpressure_btn = document.getElementById('showpressure');
            let showfallout_btn = document.getElementById('showfallout');
            let showorhide_btn = document.getElementById('show_or_hide');
            let showdetect_btn = document.getElementById('showdetectmarker');
            this.showOrHide = true;
            this.isDoseShow = true;
            this.isThermalShow = true;
            this.isPressureShow = true;
            this.isFalloutShow = true;
            this.isDetectMarkerShow = false;
            showdose_btn.innerHTML = '早期电离辐射效应:显示';
            showthermal_btn.innerHTML = '热辐射效应:显示';
            showdose_btn.innerHTML = '早期电离辐射效应:显示';
            showpressure_btn.innerHTML = '冲击波超压效应:显示';
            showfallout_btn.innerHTML = '放射性落尘剂量率:显示';
            showdetect_btn.innerHTML = '探测标记:隐藏';
            showorhide_btn.innerHTML = '显示/隐藏：'
            let mushroom = document.getElementById('mushroom');
            let crater = document.getElementById('crater');
            let error = document.getElementById('error');
            mushroom.hidden = true;
            crater.hidden = true;
            error.hidden = true;
            this.errinfo = [];
        },

        // 绑定在detonate上的事件函数
        launch(){
            // 处理输入的剂量率
            let doserates_str = this.doserates_out;
            this.doserates = [];
            let rates = doserates_str.split(/[, ，]/);
            for(let i = 0; i < rates.length; i++){
                if(rates[i])
                    this.doserates.push(parseFloat(rates[i]) * 100);
            }

            // 用于debug。输出从网页输入的数据
            this.output();

            // 清空覆盖物
            overlays.clear();

            // 检查当量是否在可计算范围内
            if(this.inputYield <= 0){
                alert('当量输入应该大于等于0。');
                return false;
            }
            else if(this.inputYield==undefined || this.inputYield==''){
                alert('请输入当量。');
                return false;
            }
            else if(this.inputYield > 1e5){
                alert('抱歉，目前只能计算当量小于100000kt的核爆效应。');
                return false;
            }
            else if(this.inputYield < 1){
                alert('抱歉，输入的当量过小。');
                return false;
            }

            overlays.init(this.inputYield);

            this.initShowOrHide();

            map.setZoom(12);

            let center = bombMarker.getPosition();
            map.setCenter(center);

            if(this.detonateType=='SurfaceBurst'){
                windMarker = new BMap.Marker(new BMap.Point(center.lng + 0.05, center.lat), {icon: myBlueIcon, title: '拖拽改变放射性落尘分布方向'});
                map.addOverlay(windMarker);
                windMarker.enableDragging();
            }
        

            // 绘制早期电离辐射环
            // 计算方法来自Nuclear Bomb Effects Computer, 早期电离辐射的计算近似认为斜边距离与地面距离相同
            if(1<=this.inputYield && this.inputYield<=20000){
                if(this.otherDoseChecked && this.inputDose){
                    if(1 <= parseFloat(this.inputDose) * 100 && parseFloat(this.inputDose) * 100 <= 1e8){ // 剂量在在 Nuclear Bomb Effects Computer 中给出的计算范围内
                        r = effects.initial_nuclear_radiation_distance(this.inputYield, parseFloat(this.inputDose) * 100, this.detonateType) * mile2m;
                        overlays.getCircle(center, r, 'dose', this.inputDose * 100, '此距离处早期电离辐射剂量为：' + parseFloat(this.inputDose) + 'Sv。', true);
                    }
                    else{ // 剂量不在计算范围内
                        this.errinfo.push('早期电离辐射效应，剂量的计算范围为0.01~1e6Sv, 输入的剂量为：' + this.inputDose + 'Sv。');
                    }
                }
                for(var i = 0; i < this.selectedDose.length; i++){
                    if(debug) console.log('dose', this.selectedDose[i])
                    r = effects.initial_nuclear_radiation_distance(this.inputYield, parseFloat(this.selectedDose[i]), this.detonateType) * mile2m;
                    if(debug) console.log('dose r', r);
                    if(r != 0 || r != NaN || r!= undefined){
                        overlays.getCircle(center, r, 'dose', this.selectedDose[i]);
                    }
                }
                overlays.drawCircles('dose', center);
            }
            else{
                this.errinfo.push('早期电离辐射效应，当量的计算范围为1~20000kt, 输入的当量为：' + this.inputYield + 'kt。');
            }

            // 绘制超压环
            var hob_ft = 0;
            let extraInfo = '';
            if(this.otherPressChecked && this.inputPress)
                this.selectedPress.push(parseFloat(this.inputPress) * atm2psi);
            if(this.ab_option == 1){
                hob_ft = psi.opt_height_for_psi_from_interpolate(this.inputYield, parseFloat(this.ab_inputPress)*atm2psi)[0];
                extraInfo = '爆炸高度为:' + (hob_ft * feet2m).toFixed(2) + 'm。';
                // hob_ft = effects.opt_height_for_psi(this.inputYield, parseFloat(this.ab_inputPress));
                // h_my = psi.opt_height_for_psi_from_interpolate(this.inputYield, parseFloat(this.ab_inputPress))[0];
            }
            else if(this.ab_option == 2){
                switch(this.ab_selectedHUnit){
                    case 0:
                        hob_ft = parseFloat(this.ab_inputHeight);  break;
                    case 1:
                        hob_ft = parseFloat(this.ab_inputHeight) * m2feet;  break;
                    case 2:
                        hob_ft = parseFloat(this.ab_inputHeight) * mile2feet;  break;
                    case 3:
                        hob_ft = parseFloat(this.ab_inputHeight) * km2feet;  break;
                }
            }
            for(var i = 0; i < this.selectedPress.length; i++){
                if(this.detonateType == 'AirBurst') {
                    if(this.ab_option == 0) {
                        r = effects.psi_distance(this.inputYield, parseFloat(this.selectedPress[i]),this.detonateType=='AirBurst') * mile2m;
                        if(debug){
                            console.log('psi', this.selectedPress[i]);
                            console.log('hob', hob_ft);
                            console.log('psi r', r);
                        }
                    } 
                    else {
                        r = psi.r_from_interpolate(this.inputYield,parseFloat(this.selectedPress[i]), hob_ft) * feet2m;
                        if(r == 0){
                            let err = '爆炸当量为:' + this.inputYield + 'kt，' 
                                    + '爆炸高度为:' + (hob_ft * feet2m).toFixed(2) + 'm，' 
                                    + '在地面上产生的超压大于等于' + (parseFloat(this.selectedPress[i]) * psi2atm).toFixed(2) + 'atm的范围为0。'
                            this.errinfo.push(err);
                        }
                        if(debug){
                            // r1 = psi.r_from_interpolate(this.inputYield,parseFloat(this.selectedPress[i]), hob_ft) * feet2m;
                            console.log('psi', this.selectedPress[i]);
                            console.log('hob', hob_ft);
                            // console.log('hob my', h_my);
                            console.log('psi r', r);
                            // console.log('psi r1', r1);
                        }
                    }
                } else {
                    // r = effects.range_from_psi_hob(this.inputYield, parseFloat(this.selectedPress[i]), 0) * feet2m;
                    r = psi.r_from_interpolate(this.inputYield, parseFloat(this.selectedPress[i]), 0) * feet2m;
                    if(debug){
                        console.log('psi', this.selectedPress[i]);
                        console.log('hob', 0);
                        console.log('psi r', r);
                    }
                }
                if(r != 0 || r != NaN || r!= undefined){
                    if(this.detonateType == 'AirBurst'){
                        if(this.ab_option == 0)
                            overlays.getCircle(center, r, 'pressure', this.selectedPress[i], extraInfo, (i == this.selectedPress.length - 1)&&this.otherPressChecked&&this.inputPress, 'AirBurst_0');
                        if(this.ab_option == 1)
                            overlays.getCircle(center, r, 'pressure', this.selectedPress[i], extraInfo, (i == this.selectedPress.length - 1)&&this.otherPressChecked&&this.inputPress, 'AirBurst_1');
                        if(this.ab_option == 2)
                            overlays.getCircle(center, r, 'pressure', this.selectedPress[i], extraInfo, (i == this.selectedPress.length - 1)&&this.otherPressChecked&&this.inputPress);
                    }
                    else{
                        overlays.getCircle(center, r, 'pressure', this.selectedPress[i], '', (i == this.selectedPress.length - 1)&&this.otherPressChecked&&this.inputPress);
                    }
                }
            };
            if(this.otherPressChecked)
                this.selectedPress.pop();
            overlays.drawCircles('pressure');

            // 绘制热辐射环
            if(this.inputYield > 20000)
                        this.errinfo.push('当量大于20000kt，烧伤程度所对应的Q不准确。');
            if(this.otherHeatChecked && this.inputHeat){
                let d = effects.thermal_distance(this.inputYield, this.inputHeat, this.detonateType=='AirBurst') * mile2m;
                if(this.detonateType == 'AirBurst')
                    r = Math.sqrt(d * d - Math.pow(hob_ft * feet2m, 2));
                else
                    r = d;
                overlays.getCircle(center, r, 'thermal', 'other', '该距离处单位面积热量为：' + this.inputHeat + 'cal/cm^2', true, parseFloat(this.inputHeat));
            }
            for(var i = 0; i < this.selectedHeat.length; i++){
                if(debug) console.log('thermal', this.selectedHeat[i]);
                let d = effects.thermal_distance(this.inputYield, this.selectedHeat[i], this.detonateType=='AirBurst') * mile2m;
                // 如果为空爆，且知道爆炸高度，则将斜边距离转化为地面距离；
                // 如果为空爆，但选择了最大化所有超压范围，即爆炸高度不固定，近似认为斜边距离等于地面距离（从各烧伤程度对应距离的计算结果来看，这样的近似是合理的）
                if(this.detonateType == 'AirBurst' && hob_ft)
                    r = Math.sqrt(d * d - Math.pow(hob_ft * feet2m, 2));
                else
                    r = d;
                if(debug) console.log('thermal r', r);
                if(r != 0 || r != NaN || r!= undefined){
                    let Q = effects.thermal_radiation_param_q(this.inputYield, this.selectedHeat[i]);
                    overlays.getCircle(center, r, 'thermal', this.selectedHeat[i], '该距离处单位面积热量为：' + Q.toFixed(2) + 'cal/cm^2', false, Q);
                }
            }
            overlays.drawCircles('thermal', center);

            // 绘制火球环
            if(this.selectFireball){
                r = effects.fireball_radius(this.inputYield, this.detonateType=='AirBurst') * mile2m;
                if(r != 0 || r != NaN || r!= undefined){
                    overlays.getCircle(center, r, 'fireball', 0, '：' + r.toFixed(2) + 'm。', false);
                }
            }
            overlays.drawCircles('fireball');

            // 绘制放射性落尘剂量率等值线
            sfss.init(this.inputYield, parseFloat(this.inputFissionFc)/100, parseFloat(this.inputWindV) * mps2mph, parseFloat(this.inputWindA), this.doserates ,center.lng, center.lat);
            if(this.detonateType == 'SurfaceBurst' && this.checkFallout){
                if(debug) console.log(sfss.contours_data);
                if(debug) console.log(sfss.contours_point);
                for(let i = 0; i < this.doserates.length; i++){
                    if(sfss.contours_point[i].length == 0){
                        this.errinfo.push('绘制放射性落尘剂量率为' + (parseFloat(this.doserates[i])/100).toFixed(2) + 'Gy/h的等值线失败。');
                    }
                    overlays.getPolygon(sfss.contours_point[i], this.doserates[i]);
                }
                overlays.drawPolygon();
            }

            // 添加事件：windMarker拖拽后改变落尘分布方向，重新绘制
            let that = this;
            windMarker.addEventListener('dragend', function(e){
                if(that.detonateType == 'SurfaceBurst'){
                    // 利用arctan函数求与东方向的夹角
                    let angle;
                    if(e.point.lng > center.lng)
                        angle = Math.atan((e.point.lat - center.lat)/(e.point.lng - center.lng)) / Math.PI * 180;
                    else if(e.point.lng < center.lng && e.point.lat > center.lat){
                        console.log(2);
                        angle = Math.atan((e.point.lat - center.lat)/(e.point.lng - center.lng)) / Math.PI * 180 + 180;
                    }
                    else if(e.point.lng < center.lng && e.point.lat < center.lat){
                        angle = Math.atan((e.point.lat - center.lat)/(e.point.lng - center.lng)) / Math.PI * 180 - 180;
                    }
                    sfss.init(that.inputYield, parseFloat(that.inputFissionFc)/100, parseFloat(that.inputWindV), angle, that.doserates ,center.lng, center.lat);
                    overlays.clearFallout();
                    for(let i = 0; i < that.doserates.length; i++){
                        overlays.getPolygon(sfss.contours_point[i], that.doserates[i]);
                    }
                    overlays.drawPolygon();
                }
            })
            

            // 蘑菇云大小
            if(this.selectMushroom){
                let mushroomhml = document.getElementById('mushroom');
                let mushroom_dsc = document.getElementById('mushroom_dsc');
                mushroomhml.hidden = false;
                this.mushroom_a = sfss.mushroomsize.a * feet2m;
                this.mushroom_b = sfss.mushroomsize.b * feet2m;
                this.mushroom_h = sfss.mushroomsize.h * feet2m;
                this.mushroom_rs = sfss.mushroomsize.r_s * feet2m;
                mushroom_dsc.innerHTML = '<p>稳定时，蘑菇云大小估计为：</p>'
                                            + '<ul>'
                                            + '<li style="margin-top:1rem">H: ' + (this.mushroom_h +  this.mushroom_b / 2).toFixed(2) + 'm</li>'
                                            + '<li style="margin-top:1rem">a: ' + this.mushroom_a.toFixed(2) + 'm</li>'
                                            + '<li style="margin-top:1rem">b: ' +  this.mushroom_b.toFixed(2) + 'm</li>'
                                            + '</ul>';
            }

            // 弹坑大小
            if(this.selectCrater && this.detonateType == 'SurfaceBurst'){
                let craterhml = document.getElementById('crater');
                craterhml.hidden = false;
                let crater_dsc = document.getElementById('crater_dsc');
                let crater = effects.crater(this.inputYield, false);
                this.crater_outr = crater[0];
                this.crater_insider = crater[1];
                this.crater_depth = crater[2];
                crater_dsc.innerHTML = '<p>假设地表为土壤，地面爆炸产生的弹坑的大小估计为：</p>'
                                        + '<ul>'
                                        + '<li style="margin-top:1rem">depth: ' + (crater[2]*mile2m).toFixed(2) + 'm</li>'
                                        + '<li style="margin-top:1rem">r: ' + (crater[1]*mile2m).toFixed(2) + 'm</li>'
                                        + '<li style="margin-top:1rem">R: ' +  (crater[0]*mile2m).toFixed(2) + 'm</li>'
                                        + '</ul>';
            }

            // 对周边设施的影响
            if(this.selectAround){
                localsearch = new BMap.LocalSearch(map, {renderOptions: {map: map, autoViewport: false}});
                let around_r;
                if(this.detonateType == 'AirBurst'){
                    if(this.ab_option == 0) {
                        around_r = effects.psi_distance(this.inputYield, 5,this.detonateType=='AirBurst') * mile2m;
                    }
                    else{
                        around_r = psi.r_from_interpolate(this.inputYield,5, hob_ft) * feet2m;
                        if(r == 0){
                            let err = '对周边设施的影响:爆炸当量为：' + this.inputYield + 'kt,' 
                                    + '爆炸高度为:' + (hob_ft * feet2m).toFixed(2) + 'm, ' 
                                    + '在地面上产生的超压大于等于' + (5 * psi2atm).toFixed(2) + 'atm的范围为0。'
                            this.errinfo.push(err);
                        }
                    }
                }
                else{
                    around_r = psi.r_from_interpolate(this.inputYield, 5, 0) * feet2m;
                }
                if(r != 0 || r != NaN || r!= undefined)
                    localsearch.searchNearby(this.facility, center, around_r);
            }

            // 添加探测标记及事件函数
            detectMarker = new BMap.Marker(new BMap.Point(bombMarker.getPosition().lng - 0.05,bombMarker.getPosition().lat - 0.05), {icon: myGreenIcon, title: '点击查看此处的效应值'});
            detectMarker.addEventListener('dragend', function(e){
                let d = map.getDistance(bombMarker.getPosition(), e.point) * m2mile; 
                let d_slant;
                if(that.detonateType=='AirBurst'){
                    d_slant = Math.sqrt(Math.pow(d*mile2m, 2) + Math.pow(hob_ft*feet2m, 2)) * m2mile;
                }
                else
                    d_slant = d;             
                let message = '';
                if(that.inputYield){
                    let dose = (effects.initial_nuclear_radiation(d_slant, that.inputYield, that.detonateType=='AirBurst')/100).toFixed(4);
                    let Q = (effects.thermal_radiation_q(d_slant, that.inputYield, that.detonateType=='AirBurst')).toFixed(2);
                    let pressure;
                    if(that.detonateType=='AirBurst'){
                        pressure = psi.psi_from_interpolate(that.inputYield, hob_ft, d * mile2feet);
                        if(pressure != '大于680atm'){
                            pressure = (pressure * psi2atm).toFixed(2);
                        }
                    }
                    else{
                        pressure = psi.psi_from_interpolate(that.inputYield, 0, d * mile2feet);
                        if(pressure != '大于680atm'){
                            pressure = (pressure * psi2atm).toFixed(2);
                        }
                    }
                    message+= '<h style="font-size: 1rem">' + '距爆心地面距离: '  + (d*mile2m/1000).toFixed(2) + 'km。</h><ul style="font-size: 0.8rem"> ';
                    if(dose!=NaN && dose!=undefined)
                        message +='<li style="margin-top: 0.5rem">早期电离辐射剂量为' + dose +'Sv</li>'
                    if(Q!=NaN && Q!=undefined)
                        message +='<li style="margin-top: 0.5rem">单位面积热量为' + Q +'cal/cm^2</li>'
                    if(pressure!=NaN && pressure!=undefined)
                        message +='<li style="margin-top: 0.5rem">此距离处超压值为' + pressure +'atm</li>'
                    message += '</ul>';
                    that.detectInfowindow= new BMap.InfoWindow(message, {
                        width : 150,     // 信息窗口宽度
                        height: 140,     // 信息窗口高度
                        offset: new BMap.Size(0, -20)
                    })
                    map.openInfoWindow(that.detectInfowindow, e.point);
                }
            });
            detectMarker.addEventListener('click', function(e){
                map.openInfoWindow(that.detectInfowindow, e.point);
            })
            detectMarker.addEventListener('dragstart', function(){
                map.closeInfoWindow();
            })
            map.addOverlay(detectMarker);
            detectMarker.enableDragging();
            detectMarker.hide();

            // 输出错误信息
            if(this.errinfo.length > 0){
                let error = document.getElementById('error');
                error.hidden = false;
                err_info = document.getElementById('errinfo');
                let infohml = '<ul>';
                for(let i = 0; i < this.errinfo.length; i++){
                    infohml += '<li style="margin-top:0.5rem">' + this.errinfo[i] + '</li>';
                }
                infohml += '</ul>';
                err_info.innerHTML = infohml;
            }

            if(debug) console.log('errinfo', this.errinfo);

            // 滚动到setting的底部
            let ele = document.createElement("div");
            document.getElementById('setting').append(ele);
            ele.scrollIntoView();

        },

        setMapCenter(location) {
            if(debug) console.log('setMapCenter:mapcenter, before:', map.getCenter());
            map.setCenter(location);
            setTimeout(function() {
                            if(debug) console.log('setMapCenter:mapcenter, after:', map.getCenter());
                            bombMarker.setPosition(map.getCenter());
                            map.setZoom(15);
                            map.clearOverlays();
                       }, 500);
        },

        setChooseLocation() {
            this.setMapCenter(this.selectedLocation);
            this.initSetting();
            overlays.clear();
        },

        setInputCity(){
           this.setMapCenter(this.inputCity);
           this.initSetting();
            overlays.clear();
        },

        setInputPosi(){
            let posi = new BMap.Point(this.inputLng, this.inputLat);
            this.setMapCenter(posi);
            this.initSetting();
             overlays.clear();
         },
 
        toggleFooter(){
            let setting_area = document.getElementById('setting_container');
            let setting_open = document.getElementById('setting_open');
            let setting_close = document.getElementById('setting_close');
            if (setting_area.hidden) { // 如果已经关闭，则打开
                setting_area.hidden = false;
                setting_open.style.visibility = 'hidden';
                setting_close.style.visibility = 'visible';
            } else {
                setting_area.hidden = true;
                setting_open.style.visibility = 'visible';
                setting_close.style.visibility = 'hidden';
            }
        },

        showMore(){
            let moresetting = document.getElementById('moresetting');
            let showArrow = document.getElementById('showMore');
            if(moresetting.hidden){
                showArrow.innerHTML = '▼';
                moresetting.hidden = false;
            }
            else{
                showArrow.innerHTML = '▶';
                moresetting.hidden = true;
            }
        },

        showorhide(){
            let showdose_btn = document.getElementById('showdose');
            let showthermal_btn = document.getElementById('showthermal');
            let showpressure_btn = document.getElementById('showpressure');
            let showfallout_btn = document.getElementById('showfallout');
            let showorhide_btn = document.getElementById('show_or_hide');
            let showdetect_btn = document.getElementById('showdetectmarker');

            if(this.showOrHide){
                this.showOrHide = false;
                showorhide_btn.innerHTML = '显示/隐藏'
                showdose_btn.hidden = true;
                showthermal_btn.hidden = true;
                showpressure_btn.hidden = true;
                showfallout_btn.hidden = true;
                showdetect_btn.hidden = true;
            }
            else{
                this.showOrHide = true;
                showorhide_btn.innerHTML = '显示/隐藏:'
                showdose_btn.hidden = false;
                showthermal_btn.hidden = false;
                showpressure_btn.hidden = false;
                showfallout_btn.hidden = false;
                showdetect_btn.hidden = false;
            }

        },

        showDose(){
            let showdose_btn = document.getElementById('showdose');
            if(this.isDoseShow){
                this.isDoseShow = false;
                showdose_btn.innerHTML = '早期电离辐射效应:隐藏';
                overlays.show('dose', false);
            }
            else{
                this.isDoseShow = true;
                showdose_btn.innerHTML = '早期电离辐射效应:显示';
                overlays.show('dose', true);
            }
        },

        showThermal(){
            let showthermal_btn = document.getElementById('showthermal');
            if(this.isThermalShow){
                this.isThermalShow = false;
                showthermal_btn.innerHTML = '热辐射效应:隐藏';
                overlays.show('thermal', false);
            }
            else{
                this.isThermalShow = true;
                showthermal_btn.innerHTML = '热辐射效应:显示';
                overlays.show('thermal', true);
            }
        },

        showPressure(){
            let showpressure_btn = document.getElementById('showpressure');
            if(this.isPressureShow){
                this.isPressureShow = false;
                showpressure_btn.innerHTML = '冲击波超压效应:隐藏';
                overlays.show('pressure', false);
            }
            else{
                this.isPressureShow = true;
                showpressure_btn.innerHTML = '冲击波超压效应:显示';
                overlays.show('pressure', true);
            }
        },

        showFallout(){
            let showfallout_btn = document.getElementById('showfallout');
            if(this.isFalloutShow){
                this.isFalloutShow = false;
                if(windMarker)
                    windMarker.hide();
                showfallout_btn.innerHTML = '放射性落尘剂量率:隐藏';
                overlays.show('fallout', false);
            }
            else{
                this.isFalloutShow = true;
                if(windMarker)
                    windMarker.show();
                showfallout_btn.innerHTML = '放射性落尘剂量率:显示';
                overlays.show('fallout', true);
            }
        },

        showDetectMarker(){
            if(bombMarker&&detectMarker)
                detectMarker.setPosition(new BMap.Point(bombMarker.getPosition().lng-0.05, bombMarker.getPosition().lat-0.05));
            let showdetect_btn = document.getElementById('showdetectmarker');
            if(this.isDetectMarkerShow){
                this.isDetectMarkerShow = false;
                showdetect_btn.innerHTML = '探测标记:隐藏';
                if(detectMarker)
                    detectMarker.hide();
            }
            else{
                this.isDetectMarkerShow = true;
                showdetect_btn.innerHTML = '探测标记:显示';
                if(detectMarker)
                    detectMarker.show();
            }
        },

        // 控制输入的超压值范围
        controlPresInput(){
            if(this.ab_inputPress){
                if(parseFloat(this.ab_inputPress) < 0.068 || parseFloat(this.ab_inputPress) > 680){
                    this.ab_inputPress = '';
                    alert('输入的压强范围为: 0.068~680atm。')
                }
            }
            if(this.inputPress){
                if(parseFloat(this.inputPress) < 0.068 || parseFloat(this.inputPress) > 680){
                    this.inputPress = '';
                    alert('输入的压强范围为: 0.068~680atm。')
                }
            }
        },

        // 控制输入的当量
        controlYieldInput(){
            if(this.inputYield <= 0){
                alert('当量输入应该大于等于0。');
                this.inputYield = '';
            }
            else if(this.inputYield==undefined || this.inputYield==''){
                alert('请输入当量。');
                this.inputYield = '';
            }
            else if(this.inputYield > 1e5){
                alert('抱歉，目前只能计算当量小于100000kt的核爆效应。');
                this.inputYield = '';
            }
            else if(this.inputYield < 1){
                alert('抱歉，输入的当量过小。');
                this.inputYield = '';
            }
        },

        // 获取爆炸地点风向风力
        getWind(){
            weather.init();
            weather.getLocalWeather(bombMarker.getPosition(), 0);
            let that = this;
            setTimeout(function(){
                that.inputWindV = weather.windV[0];
                that.inputWindA = weather.windA[0];
            }, 1000);
        },

        // 输出网页输入数据
        output(){
            if(debug){
                console.log('selectedLocation',this.selectedLocation);
                console.log('inputYield',this.inputYield);
                console.log('detonateType', this.detonateType);
                console.log('checkCasualty', this.checkCasualty);
                console.log('checkFallout', this.checkFallout);
                console.log('ab_option', this.ab_option);
                console.log('ab_inputPress', this.ab_inputPress);
                console.log('ab_inputHeight', this.ab_inputHeight);
                console.log('ab_selectedHUnit', this.ab_selectedHUnit);
                console.log('selectedPress', this.selectedPress);
                console.log('selectedDose', this.selectedDose);
                console.log('selectedHeat', this.selectedHeat);
                console.log('otherPressChecked', this.otherPressChecked);
                console.log('otherDoseChecked', this.otherDoseChecked);
                console.log('otherHeatChecked', this.otherHeatChecked);
                console.log('inputPress',this.inputPress);
                console.log('inputDose',this.inputDose);
                console.log('inputHeat',this.inputHeat);
                console.log('selectFireball', this.selectFireball);
                console.log('selectCrater', this.selectCrater);
                console.log('selectMushroom', this.selectMushroom);
                console.log('inputWindV',this.inputWindV);
                console.log('inputWindA',this.inputWindA);
                console.log('inputFissionFc',this.inputFissionFc);
                console.log('mile2m', mile2m);
                console.log('doserates', this.doserates);
            }
        }
    }
}

var app = Vue.createApp(App);
 
// 样式为：[查看解释] 的组件，鼠标置于其上或者点击可查看解释信息
app.component('abbr-explain',{
    props: ['info'],
    template:`
    <span>[</span>
    <abbr :title="info" @click="say()"><small>查看解释</small></abbr>
    <span>]</span>
    `,
    data () {
        return{
            text: this.info
        };
    },
    methods:{
        say(){
            alert(this.text);
        }
    }
});   

app.mount('#app')

